package Client端;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {
    public synchronized static String sendText(String cmd) {
        try {
            System.out.println("发送信息: |" + cmd + "|");
            // 和服务器创建连接
            Socket socket = new Socket("localhost", 9999);
            // 要发送给服务器的信息
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write(cmd);
            pw.flush();
            socket.shutdownOutput();
            // 从服务器接收的信息
            BufferedReader br =
                    new BufferedReader(
                            new InputStreamReader(
                                    socket.getInputStream()));
            String info;
            if ((info = br.readLine()) != null) {
                System.out.println("接受信息: |" + info.trim() + "|");
            }
            br.close();
            os.close();
            pw.close();
            socket.close();
            return info.trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("连接异常！！！");
        return "error";
    }
}
